#ifndef	_APP_C_
#define _APP_C_

#include "ca51f1_config.h"
#include "includes\ca51f1sfr.h"
#include "includes\ca51f1xsfr.h"
#include "includes\gpiodef_f1.h"

#include "app.h"
#include "adc.h"
#include "time.h"
#include "433.h"

adc_t adc = {0};
bit8	flag_mode = {0};

void gpio_init(void)
{
	P31F = INPUT|PU_EN;
	P30F = INPUT|PU_EN;
	P32F = INPUT;
	P01F = OUTPUT;
	P34F = OUTPUT;
	STOP;
}

void key_prev(void)
{
	if(!time.bits.end_time_1ms) return ;
	if(flag_lock) return ;
	
	switch (key_state)
	{
		case KEY_UP_SHORT:
			key_state = KEY_FLASE;
			if(flag_up) break;
			POS;
			break;
		case KEY_DOWN_SHORT:
			key_state = KEY_FLASE;
			if(flag_down) break;
			NEG;
			break;
		case KEY_STOP_SHORT:
			key_state = KEY_FLASE;
			STOP;
			break;
		default:
			break;
	}
}

u8 count_up_H = 0, count_up_L = 0;
u8 count_down_H = 0, count_down_L = 0;
void up_down_scan(void)
{
	if(!time.bits.end_time_1ms) return ;
	
	if(UP == 0)
	{
		count_up_L = 0;
		if(count_up_H ++ >= 20)
		{
			count_up_H = 0;
			flag_up = 1;
		}
	}
	else
	{
		count_up_H = 0;
		if(count_up_L ++ >= 20)
		{
			count_up_L = 0;
			flag_up = 0;
		}
	}
	
	if(DOWN == 0)
	{
		count_down_L = 0;
		if(count_down_H ++ >= 20)
		{
			count_down_H = 0;
			flag_down = 1;
		}
	}
	else
	{
		count_down_H = 0;
		if(count_down_L ++ >= 20)
		{
			count_down_L = 0;
			flag_down = 0;
		}
	}
}

void state_scan(void)
{
	if(flag_up != flag_up_prev)
	{
		if(flag_up)
		{
			STOP;
		}
		flag_up_prev = flag_up;
	}
	
	if(flag_down != flag_down_prev)
	{
		if(flag_down)
		{
			STOP;
		}
		flag_down_prev = flag_down;
	}
	
	if(flag_lock != flag_lock_prev)
	{
		if(flag_lock)
		{
			STOP;
		}
		flag_lock_prev = flag_lock;
	}
}

#define			LOCK_CUR			100

u8 count_lock_H = 0, count_lock_L = 0;
void adc_scan(void)
{
	if(!time.bits.end_time_10ms) return ;
	
	if(adc.index >= N)
	{
		adc.index = 0;
		adc.aver = adc.sum / N;
		adc.sum = 0;
	}
	else
	{
		adc.buf[adc.index] = adc_read();
		adc.sum += adc.buf[adc.index];
		adc.index ++;
	}
	
	if(!time.bits.end_time_100ms) return ;
	
	if(adc.aver >= LOCK_CUR)
	{
		count_lock_L = 0;
		if(count_lock_H ++ > 5)
		{
			count_lock_H = 0;
			flag_lock = 1;
		}
	}
	else
	{
		count_lock_H = 0;
		if(count_lock_L ++ > 5)
		{
			count_lock_L = 0;
			flag_lock = 0;
		}
	}
}

#endif
